﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace WP7.Extensions.Extensions
{
    public static class IEnumerableExtensions
    {
        /// <summary>
        /// Applies an Action<T> on each element in an IEnumerable<T> collection
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="sequence">The sequence to traverse</param>
        /// <param name="action">The action to perform</param>
        public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
        {
            if (sequence == null)
                throw new ArgumentNullException("The secuence is null!");

            if (action == null)
                throw new ArgumentNullException("The action is null!");

            foreach (T t in sequence)
                action(t);
        }

        /// <summary>
        /// Checks if object exists in collection
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="obj">Your object to be checked</param>
        /// <param name="collection">Collection to check against</param>
        /// <returns>True if object exists in collection</returns>
        public static bool ExistsIn<T>(this T obj, IEnumerable<T> collection)
        {
            return collection.Contains(obj);
        }

        /// <summary>
        /// Checks if collection is null or empty
        /// </summary>
        /// <typeparam name="T">Type of object in collection</typeparam>
        /// <param name="obj">Your collection</param>
        /// <returns>Returns true if collection is null or has no items</returns>
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> obj)
        {
            return obj.IsNull() || obj.Count() == 0;
        }

        /// <summary>
        /// Returns an ObservableCollection
        /// </summary>
        /// <typeparam name="T">The type the collection should hold</typeparam>
        /// <param name="source">Collection to transform</param>
        /// <returns>ObservableCollection</returns>
        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
        {
            var collection = new ObservableCollection<T>();
            source.ForEach(collection.Add);
            return collection;
        }

        public static string CreateString<T>(this IEnumerable<T> source, char separator = ' ')
        {
            string concatinatedString = string.Empty;
            source.ForEach(x => concatinatedString += separator + x.ToString());
            return concatinatedString.Trim(separator);
        }
    }
}
